package com.kuaimacode.kframework.component;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.aliyuncs.push.model.v20160801.PushRequest;
import com.aliyuncs.push.model.v20160801.PushResponse;
import com.kuaimacode.kframework.enums.DeviceTypeEnum;
import com.kuaimacode.kframework.mybatis.models.push.SysPushToken;
import com.kuaimacode.kframework.service.SysPushTokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author qinyong
 * @Title:
 * @Package com.kuaimacode.kframework.component
 * @Description: created by IntelliJ IDEA
 * @date 2019-08-25 17:48
 */
@Slf4j
@Service
public class AliPushService {

    @Value("${aliyuns.api.keyid}")
    private String accessKeyId;
    @Value("${aliyuns.api.secret}")
    private String accessKeySecret;
    @Value("${ali.push.app.key.ios}")
    private Long aliIosPushAppKey;
    @Value("${ali.push.app.key.android}")
    private Long aliAndroidPushAppKey;
    @Value("${ali.push.env:PRODUCT}")
    private String pushEnv;

    @Autowired
    private SysPushTokenService pushTokenService;

    public boolean pushByAlias(String title, String content, Long userId, Map<String, Object> custom) {
        log.info("call ali push, title: {}, content: {}, userId: {}, custom: {}", title, content, userId, JSONObject.toJSONString(custom));
        SysPushToken pushToken = pushTokenService.findByUserId(userId);
        if (pushToken == null) {
            log.warn("cannot find push alias by userId: [{}]", userId);
            return false;
        }
        if (custom == null) {
            custom = new HashMap<>(16);
        }

        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        DefaultAcsClient client = new DefaultAcsClient(profile);
        PushRequest pushRequest = new PushRequest();

        //推送目标: DEVICE:按设备推送 ALIAS : 按别名推送 ACCOUNT:按帐号推送  TAG:按标签推送; ALL: 广播推送
        pushRequest.setTarget("ALIAS");
        //根据Target来设定，如Target=DEVICE, 则对应的值为 设备id1,设备id2. 多个值使用逗号分隔.(帐号与设备有一次最多100个的限制)
        pushRequest.setTargetValue(pushToken.getPushToken());
//        pushRequest.setTarget("ALL"); //推送目标: DEVICE:推送给设备; ACCOUNT:推送给指定帐号,TAG:推送给自定义标签; ALL: 推送给全部
//        pushRequest.setTargetValue("ALL"); //根据Target来设定，如Target=DEVICE, 则对应的值为 设备id1,设备id2. 多个值使用逗号分隔.(帐号与设备有一次最多100个的限制)
        // 消息类型 MESSAGE NOTICE
        pushRequest.setPushType("NOTICE");
        // 设备类型 ANDROID iOS ALL.
        pushRequest.setDeviceType("ALL");
        // 推送配置
        // 消息的标题
        pushRequest.setTitle(title);
        // 消息的内容
        pushRequest.setBody(content);
        if (DeviceTypeEnum.IOS.getType() == pushToken.getDeviceType()) {
            // 推送目标
            pushRequest.setAppKey(aliIosPushAppKey);
            if (custom.get("type") != null) {
                //1-自动派单 2-取消 3-人工派单 4-新订单  5-催单
                int type = (int) custom.get("type");
                if (type == 1) {
                    pushRequest.setIOSMusic("paiorder.caf");
                } else if (type == 2) {
                    pushRequest.setIOSMusic("cancleorder.caf");
                } else if (type == 3) {
                    pushRequest.setIOSMusic("paiorder.caf");
                } else if (type == 4) {
                    pushRequest.setIOSMusic("neworder.caf");
                } else if (type == 5) {
                    pushRequest.setIOSMusic("cuiorder.caf");
                } else {
                    pushRequest.setIOSMusic("beep.caf");
                }
            } else {
                pushRequest.setIOSMusic("beep.caf");
            }
            pushRequest.setIOSExtParameters(JSONObject.toJSONString(custom));
            pushRequest.setIOSApnsEnv(pushEnv);
        } else if (DeviceTypeEnum.ANDROID.getType() == pushToken.getDeviceType()) {
            // 推送目标
            pushRequest.setAppKey(aliAndroidPushAppKey);
            pushRequest.setAndroidExtParameters(JSONObject.toJSONString(custom));
        }
        try {
            PushResponse pushResponse = client.getAcsResponse(pushRequest);
            log.info("ali push result: {}", JSONObject.toJSONString(pushResponse));
            return true;
        } catch (ClientException e) {
            log.info("ali push error", e);
            return false;
        }
    }
}
